package com.tianji.remark.service.impl;

import com.tianji.common.autoconfigure.mq.RabbitMqHelper;
import com.tianji.common.constants.MqConstants;
import com.tianji.common.domain.dto.LikedTimesDTO;
import com.tianji.common.utils.BeanUtils;
import com.tianji.common.utils.CollUtils;
import com.tianji.common.utils.StringUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.remark.constants.RedisConstants;
import com.tianji.remark.domain.dto.LikeRecordFormDTO;
import com.tianji.remark.domain.po.LikedRecord;
import com.tianji.remark.mapper.LikedRecordMapper;
import com.tianji.remark.service.ILikedRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.StringRedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * <p>
 * 点赞记录表 服务实现类
 * </p>
 *
 * @author liuchun
 * @since 2024-09-05
 */
@Service
public class LikedRecordServiceImpl extends ServiceImpl<LikedRecordMapper, LikedRecord> implements ILikedRecordService {


    @Autowired
    private RabbitMqHelper rabbitMqHelper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 基于Redis改造点赞业务
     * @param likeRecordFormDTO
     */
    @Override
    public void addLikeRecord(LikeRecordFormDTO likeRecordFormDTO) {
        //获取当前用户
        Long userId = UserContext.getUser();
        //判断是否点赞
        String key = RedisConstants.LIKE_BIZ_KEY_PREFIX + likeRecordFormDTO.getBizId();
        Long success = redisTemplate.opsForSet().add(key, userId.toString());
        if (success != null && success == 1) {
            //点赞成功
            Long totalLikeNum = redisTemplate.opsForSet().size(key);
            redisTemplate.opsForZSet().add(RedisConstants.LIKES_TIMES_KEY_PREFIX + likeRecordFormDTO.getBizType(), likeRecordFormDTO.getBizId().toString(), totalLikeNum);
        }else {
            //点赞失败，直接返回
            return ;
        }
    }

//    public void addLikeRecord(LikeRecordFormDTO likeRecordFormDTO) {
//        //获取当前用户
//        Long userId = UserContext.getUser();
//        //判断是否点赞
//        if (likeRecordFormDTO.getLiked()) {
//            Integer count = lambdaQuery()
//                    .eq(LikedRecord::getUserId, userId)
//                    .eq(LikedRecord::getBizId, likeRecordFormDTO.getBizId())
//                    .count();
//            if (count > 0) {
//                //已经点赞了
//                return ;
//            }
//            //没有点赞新增点赞记录
//            LikedRecord likedRecord = BeanUtils.copyBean(likeRecordFormDTO, LikedRecord.class);
//            likedRecord.setUserId(userId);
//            save(likedRecord);
//        }else {
//            //不是点赞
//            LikedRecord likedRecord = lambdaQuery()
//                    .eq(LikedRecord::getBizId, likeRecordFormDTO.getBizId())
//                    .eq(LikedRecord::getBizType, likeRecordFormDTO.getBizType())
//                    .one();
//            if (likedRecord != null) {
//                //已经点赞了，删除点赞记录
//                removeById(likedRecord);
//            }else {
//                return;
//            }
//        }
//        //统计点赞数量，发送消息
//        Integer totalLiked = lambdaQuery().eq(LikedRecord::getBizId, likeRecordFormDTO.getBizId())
//                .count();
//
//        String key = StringUtils.format(MqConstants.Key.LIKED_TIMES_KEY_TEMPLATE, likeRecordFormDTO.getBizType());
//        LikedTimesDTO msg = LikedTimesDTO.builder().likedTimes(totalLiked).bizId(likeRecordFormDTO.getBizId()).build();
//        rabbitMqHelper.send(
//                MqConstants.Exchange.LIKE_RECORD_EXCHANGE,
//                key,
//                msg
//        );
//    }

    /**
     * 批量查询是否点赞指定业务
     * @param bizIds
     * @return
     */
    @Override
    public Set<Long> listLikeRecord(List<Long> bizIds) {
        if (CollUtils.isEmpty(bizIds)) {
            return CollUtils.emptySet();
        }
        //获取当前用户
//        Long userId = UserContext.getUser();
//        List<LikedRecord> likedRecordList = lambdaQuery()
//                .eq(LikedRecord::getUserId, userId)
//                .in(LikedRecord::getBizId, bizIds)
//                .list();
        // 3.返回结果
//        return likedRecordList.stream().map(LikedRecord::getBizId).collect(Collectors.toSet());
        // 1.获取登录用户id
        Long userId = UserContext.getUser();
        // 2.查询点赞状态
        List<Object> objects = redisTemplate.executePipelined((RedisCallback<Object>) connection -> {
            StringRedisConnection src = (StringRedisConnection) connection;
            for (Long bizId : bizIds) {
                String key = RedisConstants.LIKE_BIZ_KEY_PREFIX + bizId;
                src.sIsMember(key, userId.toString());
            }
            return null;
        });
        // 3.返回结果
        return IntStream.range(0, objects.size()) // 创建从0到集合size的流
                .filter(i -> (boolean) objects.get(i)) // 遍历每个元素，保留结果为true的角标i
                .mapToObj(bizIds::get)// 用角标i取bizIds中的对应数据，就是点赞过的id
                .collect(Collectors.toSet());// 收集
    }

    /**
     * 读取点赞数并发送消息
     * @param bizType
     * @param maxBizSize
     */
    @Override
    public void readLikedTimesAndSendMessage(String bizType, int maxBizSize) {
        //拼接key
        String key = RedisConstants.LIKES_TIMES_KEY_PREFIX + bizType;
        Set<ZSetOperations.TypedTuple<String>> tuples = redisTemplate.opsForZSet().popMin(key, maxBizSize);
        if (CollUtils.isEmpty(tuples)) {
            return ;
        }
        List<LikedTimesDTO> likedTimesDTOS = new ArrayList<>(tuples.size());
        for (ZSetOperations.TypedTuple<String> tuple : tuples) {
            String bizId = tuple.getValue();
            Double likedTimes = tuple.getScore();
            if (bizId == null || likedTimes == null) {
                continue;
            }
            likedTimesDTOS.add(LikedTimesDTO.builder().bizId(Long.valueOf(bizId)).likedTimes(likedTimes.intValue()).build());
        }
        //发送消息
        rabbitMqHelper.send(
                MqConstants.Exchange.LIKE_RECORD_EXCHANGE,
                StringUtils.format(MqConstants.Key.LIKED_TIMES_KEY_TEMPLATE, bizType),
                likedTimesDTOS
        );
    }
}
